import axios from 'axios'
import localCache from '@/utils/localCache'
import router from '@/router/index'
import Vue from 'vue'

// const url = 'http://192.168.1.25:9090'
// const url = 'http://192.168.1.131:9090'
const url = 'http://192.168.1.50:9090'

// websocket
// export const messageSocket = 'ws://192.168.1.211:8003/ws/push'
// export const messageSocket = 'ws://180.142.131.35:8003/ws/push'

// su接口地址
export function request(config) {
  const instance = axios.create({
    baseURL: url,
    timeout: 10000
  })

  instance.interceptors.request.use((config) => {
    config.headers.Authorization = localCache.getItem('token')
    return config
  })
  // http response 拦截器
  instance.interceptors.response.use(
    (response) => {
      // console.log(response.data.code)
      if (response.data.code === 401) {
        localCache.deleteItem('token')
        localCache.deleteItem('name')
        router.push({
          path: '/'
        })
      }
      return response
    },
    (error) => {
      if (error.response) {
        switch (error.response.status) {
          case 401:
            // 401 清除token信息并跳转到登录页面/ 401 清除token信息并跳转到登录页面
            // 退出 登录
            localCache.deleteItem('token')
            localCache.deleteItem('name')
            router.replace({
              path: '/'
            })
            break
        }
      }
      // safari不支持undefiend错误
      return Promise.reject(error.response.data ? error.response.data : '未知错误')
    }
  )
  return instance(config)
}

// 下载
export function download(config) {
  const instance = axios.create({
    // baseURL: 'http://192.168.1.20:8003',
    baseURL: url,
    timeout: 1000000
  })
  instance.interceptors.request.use((config) => {
    config.headers.Authorization = localCache.getItem('token')
    config.headers.responseType = 'arraybuffer'
    config.headers.Accept = 'application/json'
    config.headers.ContentType = 'application/json; charset=utf-8'
    return config
  })
  return instance(config)
}

// 上传
export function baseUpload(urls, data) {
  const baseURL = url
  const loading = Vue.prototype.$loading({
    lock: true,
    text: '上传中',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  return new Promise((resolve, reject) => {
    const form = new FormData()
    for (const key in data) {
      form.append(key, data[key])
    }
    axios
      .post(baseURL + urls, form, {
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: localCache.getItem('token')
        },
        transformRequest: [
          function (data) {
            return data
          }
        ]
      })
      .then(
        (response) => {
          loading.close()
          resolve(response.data)
        },
        (err) => {
          loading.close()
          reject(err)
        }
      )
  })
}
